<template>
  <div class="chapter-list">
    <div class="header">
      <h2>{{ novelInfo.name }} - 章节管理</h2>
      <div class="operation-bar">
        <a-button type="primary" @click="showAddModal">新增章节</a-button>
        <a-button style="margin-left: 16px" @click="handleBatchUpload">批量导入</a-button>
      </div>
    </div>

    <a-table
      :columns="columns"
      :data-source="chapterList"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #action="{ record }">
        <a-space>
          <a @click="handleEdit(record)">编辑</a>
          <a @click="handlePreview(record)">预览</a>
          <a-popconfirm
            title="确定要删除这个章节吗？"
            @confirm="handleDelete(record.id)"
          >
            <a>删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      :width="800"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :form="form">
        <a-form-item label="章节标题">
          <a-input
            v-decorator="[
              'title',
              { rules: [{ required: true, message: '请输入章节标题' }] }
            ]"
          />
        </a-form-item>
        <a-form-item label="章节内容">
          <a-textarea
            v-decorator="[
              'content',
              { rules: [{ required: true, message: '请输入章节内容' }] }
            ]"
            :rows="15"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 预览弹窗 -->
    <a-modal
      title="章节预览"
      :visible="previewVisible"
      :footer="null"
      :width="800"
      @cancel="previewVisible = false"
    >
      <h3>{{ previewData.title }}</h3>
      <div class="chapter-content">{{ previewData.content }}</div>
    </a-modal>

    <!-- 批量导入弹窗 -->
    <a-modal
      title="批量导入章节"
      :visible="batchUploadVisible"
      @ok="handleBatchUploadOk"
      @cancel="batchUploadVisible = false"
    >
      <a-upload
        :file-list="fileList"
        :before-upload="beforeUpload"
        accept=".txt"
      >
        <a-button>
          <a-icon type="upload" /> 选择文件
        </a-button>
        <div class="ant-upload-hint">
          支持 .txt 格式文件，文件内容格式：章节名+换行+章节内容
        </div>
      </a-upload>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: 'ChapterList',
  data() {
    return {
      loading: false,
      modalVisible: false,
      previewVisible: false,
      batchUploadVisible: false,
      modalTitle: '新增章节',
      form: this.$form.createForm(this),
      novelInfo: {},
      columns: [
        {
          title: '章节号',
          dataIndex: 'chapterNumber',
          sorter: true
        },
        {
          title: '标题',
          dataIndex: 'title'
        },
        {
          title: '字数',
          dataIndex: 'wordCount',
          sorter: true
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          sorter: true
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          sorter: true
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' }
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      chapterList: [],
      previewData: {},
      fileList: []
    }
  },
  created() {
    this.fetchNovelInfo()
    this.fetchChapterList()
  },
  methods: {
    async fetchNovelInfo() {
      const novelId = this.$route.params.id
      try {
        // TODO: 调用API获取小说信息
        // const res = await this.$api.novel.getInfo(novelId)
        // this.novelInfo = res.data
      } catch (error) {
        this.$message.error('获取小说信息失败')
      }
    },
    async fetchChapterList() {
      this.loading = true
      try {
        // TODO: 调用API获取章节列表
        // const res = await this.$api.chapter.getList({
        //   novelId: this.$route.params.id,
        //   page: this.pagination.current,
        //   pageSize: this.pagination.pageSize
        // })
        // this.chapterList = res.data.list
        // this.pagination.total = res.data.total
      } catch (error) {
        this.$message.error('获取章节列表失败')
      }
      this.loading = false
    },
    showAddModal() {
      this.modalTitle = '新增章节'
      this.modalVisible = true
      this.form.resetFields()
    },
    handleEdit(record) {
      this.modalTitle = '编辑章节'
      this.modalVisible = true
      this.$nextTick(() => {
        this.form.setFieldsValue({
          title: record.title,
          content: record.content
        })
      })
    },
    async handleModalOk() {
      try {
        const values = await new Promise((resolve, reject) => {
          this.form.validateFields((errors, values) => {
            if (errors) {
              reject(errors)
            } else {
              resolve(values)
            }
          })
        })
        
        // TODO: 调用API保存数据
        this.modalVisible = false
        this.fetchChapterList()
      } catch (error) {
        // 表单验证失败
      }
    },
    handleModalCancel() {
      this.modalVisible = false
    },
    handlePreview(record) {
      this.previewData = record
      this.previewVisible = true
    },
    handleBatchUpload() {
      this.batchUploadVisible = true
      this.fileList = []
    },
    beforeUpload(file) {
      this.fileList = [file]
      return false
    },
    async handleBatchUploadOk() {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择要上传的文件')
        return
      }

      // TODO: 处理文件上传和解析
      this.batchUploadVisible = false
      this.fetchChapterList()
    },
    async handleDelete(id) {
      try {
        // TODO: 调用API删除章节
        this.$message.success('删除成功')
        this.fetchChapterList()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      this.fetchChapterList()
    }
  }
}
</script>

<style lang="scss" scoped>
.chapter-list {
  padding: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
    }
  }

  .chapter-content {
    white-space: pre-wrap;
    line-height: 1.8;
    font-size: 16px;
  }
}
</style> 